package impl

import (
	"context"
	"fmt"
	"github.com/starmotioncf/common/filter"
	setting2 "github.com/starmotioncf/common/setting"
	"github.com/starmotioncf/soutchatinternal/model"
	"github.com/starmotioncf/soutchatinternal/repository"
	"github.com/starmotioncf/soutchatpkg/setting"
)

type settingRepository struct {
	*repository.Repository
}

func NewSettingRepository(r *repository.Repository) repository.SettingRepository {
	return &settingRepository{
		Repository: r,
	}
}

// GetModel 获取模型
func (r *settingRepository) getModel(ctx context.Context, key string) (m *model.Setting, err error) {
	err = r.DB(ctx).Model(&model.Setting{}).Where("`key` = ?", key).Find(&m).Error
	return
}

// Get 获取一个默认值
func (r *settingRepository) Get(ctx context.Context, key string, filterEntity filter.Entity) any {
	val, _ := r.GetE(ctx, key, filterEntity)
	return val
}

func (r *settingRepository) GetE(ctx context.Context, key string, filterEntity filter.Entity) (any, error) {
	meta := setting.GetSettingFieldMeta(key)
	if meta == nil {
		return nil, fmt.Errorf("settings[%s] not found", key)
	}
	//数据库没配置，直接读默认值
	m, _ := r.getModel(ctx, key)
	if m == nil || m.Id == 0 {
		return meta.Value, nil
	}
	//先检查条件值
	if filterEntity != nil && len(m.ConditionValues) > 0 {
		for i := range m.ConditionValues {
			if m.ConditionValues[i].Filter.Verify(filterEntity) {
				//命中过滤条件直接返回
				return setting2.MakeDefaultValueE(meta.RefType, m.ConditionValues[i].Value)
			}
		}
	}
	//如果没有配置条件值，直接返回数据库配置的默认值
	return setting2.MakeDefaultValueE(meta.RefType, m.Val.Data)
}
